//
//  NetworkingTools.swift
//  sina_yl
//
//  Created by 袁量 on 2017/5/22.
//  Copyright © 2017年 袁量. All rights reserved.
//

import AFNetworking

class NetworkingTools: AFHTTPSessionManager {
    // let是线程安全的
    static let shareInstance : NetworkingTools = {
        let tools = NetworkingTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
}
// 定义枚举类型
enum RequestType : String {
    case GET = "GET"
    case POST = "POST"
}
// MARK:- 封装请求方法
extension NetworkingTools {
    func request(_ methodType : RequestType, urlString : String, parameters : [String : AnyObject], finished : @escaping (_ result : AnyObject?, _ error : NSError?) -> ()) {
        // 1.定义成功的回调闭包
//        let successCallBack = { (task : URLSessionDataTask, result : AnyObject?) -> Void in
//            finished(result, nil)
//        }
        
        // 2.定义失败的回调闭包
//        let failureCallBack = { (task : URLSessionDataTask?, error : NSError) -> Void in
//            finished(nil, error)
//        }
        
        // 3.发送网络请求
        if methodType == .GET {
            print("进行了get请求")
            get(urlString, parameters: parameters, progress: nil, success: { (task : URLSessionDataTask, result : Any?) in
                finished(result as AnyObject, nil)
            }, failure: { (task : URLSessionDataTask?, error : Error) in
                finished(nil, error as NSError)
                print("get 请求失败了\(error)")
            })

//            get(urlString, parameters: parameters, progress: nil, success: successCallBack as? (URLSessionDataTask, Any?) -> Void, failure: failureCallBack as? (URLSessionDataTask?, Error) -> Void)
            
        } else {
 
//            post(urlString, parameters: parameters, progress: nil, success: successCallBack as? (URLSessionDataTask, Any?) -> Void, failure: failureCallBack as? (URLSessionDataTask?, Error) -> Void)
           
            post(urlString, parameters: parameters, progress: nil, success: { (task : URLSessionDataTask, result : Any?) in
                finished(result as AnyObject, nil)
            }, failure: { (task : URLSessionDataTask?, error : Error) in
                finished(nil, error as NSError)
            })
        }
        
    }
}

// MARK: - 请求 token
extension NetworkingTools {
    func loadAccessToken(_ code : String, finished : @escaping (_ result : [String : AnyObject]?, _ error : NSError?) -> ()) {
        // 1.获取请求的URLString
        let urlStringToken = "https://api.weibo.com/oauth2/access_token"
        
        // 2.获取请求的参数
        let parametersToken = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "redirect_uri" : redirect_URL, "code" : code]
        
        // 3.发送网络请求
//        request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//            finished(result as? [String : AnyObject], error)
//        }
        request(.POST, urlString: urlStringToken, parameters: parametersToken as [String : AnyObject]) { (result, error) in
            finished(result as? [String : AnyObject], error)
        }
    }
}
extension NetworkingTools {
    func loadUserInfo(_ token : String,uid : String, finished : @escaping (_ result : [String : AnyObject]?, _ error : NSError?) -> ()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token" : token, "uid" : uid]
        request(.GET, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) in
             finished(result as? [String : AnyObject], error) 
        }
        
    }
}
extension NetworkingTools {
    func loadStatuses(max_id : Int, since_id : Int, finished : @escaping (_ result : [[String : AnyObject]]?, _ error : NSError?) -> ()) {
        print("max_id\(max_id) 和 since_id \(since_id)")
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameters = ["access_token" : (UserAccountViewModel.shareIntance.account?.access_token)!,"max_id" : (max_id) , "since_id" : (since_id)] as [String : Any]
        request(.GET, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) in
            guard let resultDict = result as? [String : AnyObject] else {
                finished(nil, error)
                return
            }
            finished(resultDict["statuses"] as? [[String : AnyObject]], error)
        }
    }
}
// MARK:- 发送微博
extension NetworkingTools {
    func sendStatus(statusText : String, isSuccess : @escaping (_ isSuccess : Bool) -> ()) {
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        // 2.获取请求的参数
        let parameters = ["access_token" : (UserAccountViewModel.shareIntance.account?.access_token)!, "status" : statusText]
        
        // 3.发送网络请求
        request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
            if result != nil {
                isSuccess(true)
            } else {
                isSuccess(false)
            }
        }
    }
}


// MARK:- 发送微博并且携带照片
extension NetworkingTools {
    func sendStatus(statusText : String, image : UIImage, isSuccess : @escaping (_ isSuccess : Bool) -> ()) {
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/statuses/upload.json"
        
        // 2.获取请求的参数
        let parameters = ["access_token" : (UserAccountViewModel.shareIntance.account?.access_token)!, "status" : statusText]
        
        // 3.发送网络请求
        post(urlString, parameters: parameters, constructingBodyWith: { (formData) -> Void in
            
            if let imageData = UIImageJPEGRepresentation(image, 0.5) {
                formData.appendPart(withFileData: imageData, name: "pic", fileName: "123.png", mimeType: "image/png")
            }
            
        }, progress: nil, success: { (_, _) -> Void in
            isSuccess(true)
        }) { (_, error) -> Void in
            print(error)
        }
    }
}
